using OpenTK;

namespace ColladaDotNet.OpenTKMapping
{
	public class OrthographicCameraOptics : CameraOptics
	{
		private double? xmag;

		private double? ymag;


		public double YMag
		{
			get
			{
				if (ymag == null)
					return xmag.Value * aspect_ratio;
				return ymag.Value;
			}
		}
		public double XMag
		{
			get
			{
				if (xmag == null)
					return ymag.Value / aspect_ratio;
				return xmag.Value;
			}
		}
		public override Matrix4d Projection
		{
			get
			{
				return GetProjection(aspect_ratio);
			}
		}

		public override Matrix4d GetProjection(double aspect)
		{
			double w, h;
			if (xmag == null)
			{
				h = ymag.Value;
				w = ymag.Value * aspect;
			} 
			else
			{
				h = xmag.Value / aspect;
				w = xmag.Value;
			}
			var m = Matrix4.CreateOrthographic((float)w * 2, (float)h * 2, (float)zNear, (float)zFar);
			return new Matrix4d(
					m.M11, m.M12, m.M13, m.M14, m.M21, m.M22, m.M23, m.M24,
					m.M31, m.M32, m.M33, m.M34, m.M41, m.M42, m.M43, m.M44);
		}

		internal override void Load(cameraOptics colladaData)
		{
			var tech = (cameraOpticsTechnique_commonOrthographic)colladaData.technique_common.Item;
			zNear = tech.znear.Value;
			zFar = tech.zfar.Value;
			for (int i = 0; i < tech.Items.Length; i++)
			{
				var item = tech.Items[i];
				switch (tech.ItemsElementName[i])
				{
					case ItemsChoiceType.xmag:
						xmag = ((TargetableFloat)item).Value;
						break;
					case ItemsChoiceType.ymag:
						ymag = ((TargetableFloat)item).Value;
						break;
					case ItemsChoiceType.aspect_ratio:
						aspect_ratio = ((TargetableFloat)item).Value;
						break;
				}
			}
			base.Load(colladaData);
		}
	}
}